<template>
   <div>
        <slot></slot>
        <div :ref="componentRef" :id="'extMap'+componentRef" :style="{height:height+'px'}"></div>
   </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
    name:'ExtMap',
    components:{},
    props:{
        componentRef:[String,Number],
        height:{
            type:Number,
            default:400
        },
        pageObject:[Object]
    
       
    },
    watch:{
        
    },
    data(){
        return{
            map:null,
            aMap:null,
            mapId:'map'
        }
    },
    computed:{
       
    },

    created(){
      this.pageObject["map"+this.componentRef] = this
    },
    mounted () {
        this.$nextTick(() => {
            this.initMap()
        })
    },
    methods:{
        getMap(){
            return this.map
        },
        setMapOption(option){
            let that = this;
            if(option && JSON.stringify(option)!="{}"){
                 that.map = new that.aMap.Map("extMap"+that.componentRef,option);
            }else{
                that.map = new that.aMap.Map("extMap"+that.componentRef,{zoom: 13,});
            }
          
            AMap.plugin(['Amap.MouseTool','AMap.CircleEditor','AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.MapType'], function () {
                //异步同时加载多个插件
                // 添加地图插件
                that.map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
                that.map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
                // that.map.addControl(new AMap.HawkEye()); // 显示缩略图
                // that.map.addControl(new AMap.Geolocation()); // 定位当前位置
                that.map.addControl(new AMap.MapType()); // 实现默认图层与卫星图,实时交通图层之间切换

                // 以下是鼠标工具插件
                // const mouseTool = new AMap.MouseTool(that.map);
                // mouseTool.rule();// 用户手动绘制折线图,测量距离
                
            }); 
        },
        getAMap(){
            return this.aMap
        },
        
        clearMap(){
            if(this.map){
                this.map.clearMap()
            }
            this.map=null 
            this.aMap=null
        },
        initMap(){
            let that = this
            if(that.map==null){
                AMapLoader.load({
                    key: "733c6d01b087356b1e271db07110e9ee",  
                    version: "1.4.15",
                    AMapUI: { version: '1.1',},
                    plugins:['Amap.MouseTool','AMap.CircleEditor','AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.MapType','AMap.3DView']
                }).then((AMap)=>{
                    that.aMap = AMap
                    that.setMapOption()
                }).catch(e => {
                    console.log(e);
                })
            }else{
                that.map.clearMap()
            }
        },
      
    },
    destroyed(){
        this.clearMap()
    }
}
</script>